package com.shxy.controller;

import com.shxy.common.entity.JsonResult;
import com.shxy.common.enums.ResultCode;
import com.shxy.common.utils.ResultTool;
import com.shxy.controller.ui.news.NewsBase;
import com.shxy.entity.user.User;
import com.shxy.entity.wlzx.Modul;
import com.shxy.entity.wlzx.News;
import com.shxy.service.IFtpService;
import com.shxy.service.INewsService;
import com.shxy.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.http.HttpHeaders;
import java.util.Date;
import java.util.List;

/**
 * 后台管理控制器
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {
    @Autowired
    private IFtpService ftpService;
    @Autowired
    private INewsService newsService;
    @Autowired
    private IUserService userService;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @PostMapping("/upload_image")
    public JsonResult<String> uploadImg(MultipartFile file, @RequestHeader(name = "X-Token", defaultValue = "0") int token) {
        System.out.println(token);
        String path = ftpService.doUpload(file, token);
        return ResultTool.success(path);
    }

    /**
     * 保存通知信息
     * @param notice
     * @return
     */
    @PostMapping("/save_notice")
    public JsonResult<Boolean> saveNotice(@RequestBody NewsBase notice) {
        // 1、根据编号查询通知信息
        News news = newsService.findNewsById(notice.getId());
        // 2、如果该通知不存在，则返回错误
        if(news == null){
            return ResultTool.fail(ResultCode.PARAM_NOT_VALID);
        }
        // 3、设置修改时间和通知内容
        news.setUpdateTime(new Date().getTime());
        news.setContent(notice.getContent());
        // 4、保存修改后的通知
        newsService.saveNews(news);
        return ResultTool.success(true);
    }

    /**
     * 保存新闻
     * @param news
     * @return
     */
    @PostMapping("/save_news")
    public JsonResult<News> saveNews(@RequestBody NewsBase news){
        // 1、检查用户名和模块是否正确
        User user = userService.getUserById(news.getAuthorId());
        Modul modul = newsService.getModulById(news.getModuleId());
        if(user == null || modul == null) {
            return ResultTool.fail(ResultCode.PARAM_NOT_VALID);
        }
        // 2、查询新闻是否存在
        News ns = newsService.findNewsById(news.getId());
        // 3、如果不存在，则创建
        if(ns == null){
            ns = new News();
        }

        System.out.println(news.getContent());

        ns.setUpdateTime(new Date().getTime());
        ns.setContent(news.getContent());
        ns.setTitle(news.getTitle());
        ns.setAuthor(user);
        ns.setModul(modul);
        // 保存新闻，返回保存后的对象
        ns = newsService.saveNews(ns);
        return ResultTool.success(ns);
    }
}
